package com.vitaf.cash.app.ui.presenter

import android.os.CountDownTimer
import com.vitaf.cash.app.common.VitafComPresenter
import com.vitaf.cash.app.configs.GombeCreditApiPath
import com.vitaf.cash.app.configs.GombeCreditApiUrl
import com.vitaf.cash.app.configs.GombeCreditApiUrl.addCommonParams
import com.vitaf.cash.app.request.IHttpCallback
import com.vitaf.cash.app.ui.view.IVitafChat
import org.json.JSONObject

class VitafChatPet(private val iView: IVitafChat?): VitafComPresenter(iView) {
    //等待时长
    private var countdownTimer: MyCountDownTimer? = null
    private var countdown = 15

    /**
     * 获取会话记录
     * page：加载页数
     * isRefresh: 是否是定时刷新
     */
    fun loadGombeCreditCustomerChatRecordAction(page: Int? = 1,isRefresh: Boolean? = false){
        val params = JSONObject().addCommonParams()
        params.put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_CHAT_PATH)
        params.put("handleType","TALK_SELECT")
        params.put("page",page)
        params.put("size",20)
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONArray("obj")
                obj?.let { array ->
                    val recordList = arrayListOf<JSONObject>()
                    for (i in 0 until array.length()){
                        val item = array.optJSONObject(i)
                        if (item.optString("talkType") == "USER"){//发送
                            item.put("itemType","itemSend")
                        } else {//接收
                            item.put("itemType","itemReceived")
                        }
                        recordList.add(item)
                    }
                    //倒序
                    if (recordList.size > 0){
                        recordList.reverse()
                    }

                    if (isRefresh == false){//加载
                        iView?.showGombeCreditChatRecordList(recordList)

                        //第一页加载成功，启动定时加载
                        if (page == 1){
                          startCountdownTimer()
                        } else {
                        }
                    } else {//定时刷新
                        iView?.showGombeCreditChatUpdaeRecordList(recordList)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                iView?.hideVitafLoading()
            }
        })
    }

    /**
     * 发送会话消息
     */
    fun sendGombeCreditCustomerChatMsgAction(text: String){
        val params = JSONObject().addCommonParams()
        params.put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_CHAT_PATH)
        params.put("handleType","TALK_INPUT")
        params.put("talkType","USER")
        params.put("talkInfo",text)
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                loadGombeCreditCustomerChatLastRecordAction()
//                val sendItem = JSONObject()
//                sendItem.put("itemType","itemSend")
//                sendItem.put("talkInfo",text)
//                sendItem.put("createTimeStamp","${System.currentTimeMillis()}")
//                iView?.insertGombeCreditNewChat(sendItem)
//                iView?.showGombeCreditSendSuccess()
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                iView?.hideVitafLoading()
            }
        })
    }

    /**
     * 获取最新的一条会话记录，只在发送成功后获取，以发送的保证最后一条信息和服务器同步
     */
    fun loadGombeCreditCustomerChatLastRecordAction(){
        val params = JSONObject().addCommonParams()
        params.put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_CHAT_PATH)
        params.put("handleType","TALK_SELECT")
        params.put("page",1)
        params.put("size",1)
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONArray("obj")
                obj?.let { array ->
                    if (array.length() > 0){
                        val sendItem = array.optJSONObject(0)
                        sendItem.put("itemType","itemSend")
                        iView?.insertGombeCreditNewChat(sendItem)
                        iView?.showGombeCreditSendSuccess()
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                iView?.hideVitafLoading()
            }
        })
    }

    /**
     * 启动倒计时
     */
    private fun startCountdownTimer() {
        if (countdownTimer != null){
            countdownTimer?.cancel()
            countdownTimer = null
        }
        countdown = 15
        //随机 15秒 等待时长
        countdownTimer = MyCountDownTimer(this, countdown * 1000, 1000)
        countdownTimer?.start()
    }

    class MyCountDownTimer(private val presenter: VitafChatPet, millisInFuture: Int, countDownInterval: Long): CountDownTimer(millisInFuture.toLong(), countDownInterval) {
        override fun onTick(millisUntilFinished: Long) {
            // 这里每隔一段时间（定时器间隔）会被调用
            presenter.countdown = (millisUntilFinished / 1000).toInt()
        }
        override fun onFinish() {
            // 倒计时完成时被调用
            presenter.startCountdownTimer()
            presenter.loadGombeCreditCustomerChatRecordAction(page = 1, isRefresh = true)
        }
    }

    fun onDestroy(){
        if (countdownTimer != null){
            countdownTimer?.cancel()
            countdownTimer = null
        }
    }
}